package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description UserServiceImpl
 * @Author KangChi Wang
 * @Date 2024-09-04
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper UserRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页查询
     *
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return {@link PageResponse }<{@link List }<{@link User }>>
     */
    @Override
    public PageResponse<UserVo> page(UserDto userDto, Integer pageNum, Integer pageSize) {


        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }

        PageHelper.startPage(pageNum, pageSize);

        Page<User> page = userMapper.selectPage(userDto);

        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);

        if (!EmptyUtil.isNullOrEmpty(pageResponse.getRecords())) {

            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);
            //装配数据
            pageResponse.getRecords().forEach(n -> {
                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                Set<String> roleVoLabels = Sets.newHashSet();
                roleVoList.forEach(r -> {
                    if (String.valueOf(n.getId()).equals(r.getUserId())) {
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVoLabels.add(r.getRoleName());
                    }
                });
                n.setRoleLabels(roleVoLabels);
                n.setRoleVoIds(roleVoIds);
            });
        }
        return pageResponse;

    }

    /**
     * 启用禁用
     * @param id
     * @param status
     */
    @Override
    public void isEnable(Long id, String status) {
        userMapper.isEnable(id, status);
    }

    /**
     * 添加用户
     * @param userDto
     * @return {@link Boolean }
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Boolean save(UserDto userDto) {
        //类型转换

        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(user.getEmail());
        user.setNickName(user.getRealName());
        user.setDataState(SuperConstant.DATA_STATE_0);
        user.setPassword("123456");
        //保存用户基本信息
        int flag =userMapper.insert(user);
        if(flag==0){
            throw new RuntimeException("保存用户信息出错");
        }
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(n -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(n))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        flag = UserRoleMapper.batchInsert(userRoles);
        if(flag==0){
            throw new RuntimeException("保存用户角色信息出错");
        }

        return true;

    }

    @Override
    public void remove(Long userId) {
        //先删除中间表
        UserRoleMapper.dele(userId);
        //删除用户
        userMapper.deleteByPrimaryKey(userId);
    }

}
